<template>
	<div class="app-center">
		<div class="loading" v-if="categoryList.length==0"><span class="el-icon-loading"></span>拼命加载中</div>
		<div v-for="(item, index) in mergeCateAppInfo" :key="index">
			<h3>{{ item.cat_name }}<span></span></h3>
			<div class="noapp disabled" v-if="!item.appInfo"><span class="el-icon-warning"></span>暂无应用</div>
			<el-row>
				<el-col :span="4" v-for="(item2, index2) in item.appInfo" :key="index2">
					<el-card :body-style="{ padding: '10px' }">
						<div ref='photobox' class="photobox">
							<span class="icon iconfont icon-nopic" v-if="!item2.preview"></span>
							<img :src="item2.preview" class="image" v-if="item2.preview">
						</div>
						<div style="padding: 14px;">
							<!-- <span>{{ item2.app_name }}</span> -->
							<div class="bottom clearfix">
								<time class="time">{{ item2.app_name }}</time>
								<el-button type="success" class="button" @click="open(item2.app_info_id, item2.app_name)" v-if="appInfoForm.auth">购买</el-button>
							</div>
						</div>
					</el-card>
				</el-col>
			</el-row>
		</div>
		<!-- 购买应用 开始 -->
		<el-dialog :title="'购买《' + dialog.title + '》'" :visible.sync="dialog.visible" :close-on-click-modal="false" width="460px">
			<el-form :model="appInfoForm" :rules="rules" ref="appInfoForm" label-width="100px">
				<input type="hidden" :value="appInfoForm.data.app_info_id">
				<el-form-item label="应用名称" prop="data.app_name" style="width: 378px;">
					<el-input v-model="appInfoForm.data.app_name" placeholder="应用名称"></el-input>
				</el-form-item>
				<el-form-item label="描述" prop="data.describe" style="width: 378px;">
					<my-textarea ref="mytextarea" :rows=3 :value="appInfoForm.data.describe" @changeTextarea="changeTextarea" :limit="50"></my-textarea>
				</el-form-item>
				<el-form-item label="购买年限" prop="data.buyTime">
					<el-select v-model="appInfoForm.data.buyTime" placeholder="请选择购买年限，推荐购买三年！" style="width: 278px;">
						<el-option v-for="(item, index) in appInfoForm.yearPrice" :key="index" :label="item.year+'年'" :value="item.year"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="价格" style="width: 378px;">
					￥<span ref='price'>0</span>元（原价：￥<span ref='originPrice' style="text-decoration: line-through;">0</span>元） 
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialog.visible = false">取 消</el-button>
				<el-button type="primary" @click="submitForm('appInfoForm')" :disabled='appInfoForm.submitLock'>
					确 定 <span class="el-icon-loading" v-if='appInfoForm.submitLock'></span>
				</el-button>
			</div>
		</el-dialog>
		<!-- 购买应用 结束 -->
	</div>
</template>

<script>
import {changeToBool, judgeAuth} from "static/js/common.js"
import MyTextarea from "common/Textarea"
import {domain} from '@/api';
import {mapGetters} from 'vuex'

export default {
	inject: ['reload'],
	data() {
		return {
			/*列表数据*/
			appInfoList: [
				// {
				// 	app_info_id: 1,
				// 	app_name: '我的面板',
				// 	app_cat_id: 1,
				// 	icon: 'panel',
				// 	app_url: 'panel',
				// 	outside: 'panel',
				// 	preview: 'https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png',
				// 	display: false,
				// },
			],
			level: 0,//用户等级
			/*分类列表数据*/
			categoryList: [],
			dialog: {
				'title': '',
				'visible': false,
				'tpl': [],
			},
			/*购买数据*/
			appInfoForm: {
				submitLock: false,
				auth: false,//购买权限
				yearPrice: [
					// {
					// 	'year': 1,//年限
					// 	'price': 111,//价格
					// },
					// {
					// 	'year': 2,//年限
					// 	'price': 222,//价格
					// },
					// {
					// 	'year': 3,//年限
					// 	'price': 333,//价格
					// }
				],
				data: {
					app_info_id: 0,
					app_name: '',
					describe: '',
					buyTime: '',
				}
			},
			rules: {
				data: {
					app_name: [
						{ required: true, message: '请输入应用名称', trigger: 'blur' },
						{ min: 3, max: 16, message: '长度在 3 到 16 个字符', trigger: 'blur' }
					],
					buyTime: [
						{ required: true, message: '请输入购买时长', trigger: 'change' }
					]
				}
			}
		};
	},
	components: {
		MyTextarea
	},
	created: function() {
		/*获取分类数据*/
		this.getCategoryList()
		/*获取列表数据*/
		this.getAppInfoList()
		// console.log(this.$getBaseURL())\
		/*权限判断显示*/
		this.appInfoForm.auth = (judgeAuth('buyApp', this.allMenuList) == undefined)?false:true

		/*取出用户信息，用户计算价格*/
		let level;
		if(level = JSON.parse(this.$localstorage.get('uinfo')).level){
			this.level = level
		}
	},
	methods: {
		/*获取分类数据*/
		getCategoryList: function(){
			if(this.$api.appCategoryList != undefined){
				// this.$baseURL('http://super.ac.comdd')
				this.$baseURL(domain.ac)
				this.$get(this.$api.appCategoryList, {
					'display': 2
				}).then(res => {
					// console.log(res);
					// if(res.data.code == 10007){//后台提示需要登录
					// 	this.$cookie.remove('isLogin');//刪除cookie登录信息
					// 	this.reload();
					// }
					if(res.data.code === 0){
						if(res.data.data != undefined){
							this.categoryList = []
							Object.keys(res.data.data).forEach((k) => {
								this.categoryList.push ({
									app_cat_id: res.data.data[k].app_cat_id,
									cat_name: res.data.data[k].cat_name,
									icon: res.data.data[k].icon,
									display: changeToBool(res.data.data[k].display)
								});
							})
						}
					}
				})
				.catch(err => {})
				.finally(() => {}) 
			}else{
				this.$message({
					showClose: true,
					message: '您没有[应用分类]权限',
					type: 'error'
				});
			}
		},
		/*获取列表数据*/
		getAppInfoList: function(){
			if(this.$api.appCategoryList != undefined && this.$api.appInfoList != undefined){
				this.$baseURL(domain.ac)
				this.$get(this.$api.appInfoList, {
					'display': 2
				}).then(res => {
					// console.log(res);
					// if(res.data.code == 10007){//后台提示需要登录
					// 	this.$cookie.remove('isLogin');//刪除cookie登录信息
					// 	this.reload();
					// }
					if(res.data.code === 0){
						if(res.data.data != undefined){
							this.appInfoList = []
							Object.keys(res.data.data).forEach((k) => {
								this.appInfoList.push ({
									app_info_id: res.data.data[k].app_info_id,
									app_name: res.data.data[k].app_name,
									app_cat_id: (res.data.data[k].category != null)?res.data.data[k].category.app_cat_id:'',
									icon: res.data.data[k].icon,
									app_url: res.data.data[k].app_url,
									outside: res.data.data[k].outside,
									preview: res.data.data[k].preview,
									display: changeToBool(res.data.data[k].display)
								});
							})
						}
						this.tableLoading = false
					}
				})
				.catch(err => {})
				.finally(() => {}) 
			}else{
				this.$message({
					showClose: true,
					message: '您没有[应用列表]权限',
					type: 'error'
				});
			}
		},
		/*
		购买弹窗
		id 		
		title 	应用名称
		*/
		open: function(id, title){
			if(this.$api.modifyAppinfo != undefined){
				// console.log(id)
				this.appInfoForm.submitLock = true;
				this.dialog.visible = !this.dialog.visible
				this.appInfoForm.data.app_info_id = id
				this.dialog.title = title
				this.$nextTick(() => {
					this.$refs.appInfoForm.resetFields()//清空表单
					this.$refs.price.innerHTML = 0
					this.appInfoForm.data.describe = ''
					this.$refs.mytextarea.initDescribe(this.appInfoForm.data.describe)//初始化子组件的值
				})

				this.$baseURL(domain.ac)
				this.$get(this.$api.modifyAppinfo, {
					'id': id
				}).then(res => {
					// if(res.data.code == 10007){//后台提示需要登录
					// 	this.$cookie.remove('isLogin');//刪除cookie登录信息
					// 	this.reload();
					// }
					if(res.data.code == 0){
						// console.log(res.data.data)
						/*填充价格*/
						this.appInfoForm.yearPrice = []
						Object.keys(res.data.data.price).forEach((k) => {
							this.appInfoForm.yearPrice.push ({
								year: res.data.data.price[k].year,
								price: res.data.data.price[k].price
							});
						})

					}else{
						this.$message({
							showClose: true,
							message: res.data.info,
							type: 'error'
						});
					}
					this.appInfoForm.submitLock = false;
				})
				.catch(err => {})
				.finally(() => {}) 
			}
		},
		/*提交购买表单*/
		submitForm(formName) {
			if(!this.appInfoForm.submitLock && this.$api.buyApp != undefined){
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.appInfoForm.submitLock = true;
						this.$baseURL(domain.ac)
						this.$post(this.$api.buyApp, {
							App: this.appInfoForm.data
						}).then(res => {
							// console.log(res);
							/*成功*/
							// if(res.data.code == 10007){//后台提示需要登录
							// 	this.$cookie.remove('isLogin');//刪除cookie登录信息
							// 	this.reload();
							// }
							if(res.data.code == 0){
								this.$message({
									showClose: true,
									message: res.data.info,
									type: 'success'
								});
								this.dialog.visible = false//关闭dialog
							}else{
								this.$message({
									showClose: true,
									message: res.data.info,
									type: 'error'
								});
							}
							this.appInfoForm.submitLock = false;
						});
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			}
		},
		/*修改文本域的内容，给子组件调用*/
		changeTextarea(v){
			this.appInfoForm.data.describe = v
		},
	},
	watch: {
    	/*选择年限*/
		'appInfoForm.data.buyTime': function(val){
			//更改显示总价格
			if(val){
				// console.log(val)
				for(let i=0; i<this.appInfoForm.yearPrice.length; i++){
					if(this.appInfoForm.yearPrice[i].year == val){
						this.$refs.originPrice.innerHTML = this.appInfoForm.yearPrice[i].price//计算原价
						if(this.level == 0){//普通等级，计算折扣价
							switch(val){
								case '1':
									this.$refs.price.innerHTML = this.appInfoForm.yearPrice[i].price
									break;
								case '2':
									this.$refs.price.innerHTML = this.appInfoForm.yearPrice[i].price*0.9
									break;
								case '3':
									this.$refs.price.innerHTML = this.appInfoForm.yearPrice[i].price*0.8
									break;
								case '5':
									this.$refs.price.innerHTML = this.appInfoForm.yearPrice[i].price*0.7
									break;
								case '10':
									this.$refs.price.innerHTML = this.appInfoForm.yearPrice[i].price*0.6
									break;
							}

						}else if(this.level == 1){//一级，最高等级
							this.$refs.price.innerHTML = this.appInfoForm.yearPrice[i].price*0.1
						}else{//其他等级  二级和三级
							switch(val){
								case '1':
									this.$refs.price.innerHTML = this.appInfoForm.yearPrice[i].price*(this.level/10)
									break;
								case '2':
									this.$refs.price.innerHTML = this.appInfoForm.yearPrice[i].price*(this.level/10)*0.9
									break;
								case '3':
									this.$refs.price.innerHTML = this.appInfoForm.yearPrice[i].price*(this.level/10)*0.8
									break;
								case '5':
									this.$refs.price.innerHTML = this.appInfoForm.yearPrice[i].price*(this.level/10)*0.7
									break;
								case '10':
									this.$refs.price.innerHTML = this.appInfoForm.yearPrice[i].price*(this.level/10)*0.6
									break;
							}

						}
					}
				}
			}
		}
    },
	computed: {
		...mapGetters([
			'allMenuList'
		]),
		/*分类数据 应用数据 整合*/
		mergeCateAppInfo: function () {
			for(let i=0; i<this.categoryList.length; i++){
				for(let j=0; j<this.appInfoList.length; j++){
					if(this.categoryList[i].app_cat_id == this.appInfoList[j].app_cat_id){
						if(this.categoryList[i].appInfo == undefined){
							this.categoryList[i].appInfo = []
						}
						this.categoryList[i].appInfo.push(this.appInfoList[j])
					}
				}
			}
			return this.categoryList
		},
	}
};
</script>

<style lang="stylus" scoped>
@import "../../../../static/css/variable.styl"
.app-center
	// height: 100%
	.loading
		width: 100%
		height: 100%
		padding-top: 80px
		text-align: center
		.el-icon-loading
			margin-right: 5px
	.noapp
		text-align: center
		.el-icon-warning
			margin-right: 5px
	h3
		text-align: center
		margin: 35px 0
		span
			display: block
			width: 30px
			margin: 8px auto 0
			padding: 1px 15px
			background: $theme-color
	.el-col
		width: 250px
		margin: 0 10px 15px
		.el-card
			width: 100%
			.time
				font-size: 13px
				color: #999
			.bottom
				margin-top: 13px
				line-height: 20px
				height: 20px
			.button 
				padding: 3px 8px
				float: right
			.photobox
				display: block
				width: 230px
				height: 230px
				position: relative
				.image
					max-height: 230px
					max-width: 230px
					display: block
					position: absolute
					margin-top: 50%
					margin-left: 50%
					transform: translateX(-50%) translateY(-50%)
				.image+div
					padding: 14px 0 5px !important
			.clearfix:before,.clearfix:after
				display: table
				content: ""
			.clearfix:after
				clear: both
.icon-nopic
	display: block
	width: 100%
	height: 100%
	padding-top: 33%
	color: #ebebeb
	font-size: 50px
	text-align: center
	box-sizing: border-box
	cursor: pointer
	position: relative
</style>